module key_debounce(
    input sys_clk,
    input sys_rst_n, 
    input key,

    output reg key_value,
    output reg key_flag
);

reg [25:0] cnt;
reg key_reg;

always @(posedge sys_clk or negedge sys_rst_n) begin
    if(!sys_rst_n) begin
        cnt <= 0;
    end
    else begin
        key_reg <= key;
        if(key_reg != key)
            cnt <= 25'd10;
        else
            if(cnt > 1'b0)
                cnt <= cnt - 1'b1;
            else
                cnt <= 1'b0;
    end
end

always @(posedge sys_clk or negedge sys_rst_n) begin
    if(!sys_rst_n) begin
        key_value <= 1'b1;
        key_flag <= 1'b0;
    end
    else if(cnt == 1'b1) begin
        key_value <= key;
        key_flag <= 1'b1;
    end
    else begin
        key_value <= key_value;
        key_flag <= 1'b0;
    end
end

endmodule